import { intl } from '@/utils';
import { Radio } from 'antd';
import { Button, Popup, SelectBox, TextArea } from 'devextreme-react';
import notify from 'devextreme/ui/notify';
import React, { useCallback, useImperativeHandle, useRef, useState } from 'react';
import { useModel } from 'umi';
import CpasTableFs from '~/public/cpas-business/cpas-table/CpasTableFs';

const PopupDevComponentsFormalu = React.forwardRef((props: any, ref: any) => {
  const [visible, setVisible] = useState<boolean>(false);
  const popupRef = useRef<any>(null);
  const diaParams = useRef<any>();
  const { initialState } = useModel('@@initialState');
  const [isFormulaModalOpen, setIsFormulaModalOpen] = useState(false);
  const { dbname, sjnd } = initialState?.curPart;
  const { cpasTableZeroReplace } = initialState?.settings;
  const [CalculationFormulaSystem, setCalculationFormulaSystem] = useState('');

  const CalculationFormula = useRef<any>('');

  const [createTabla, setCreateTabla] = useState('资产表');
  const cpasTableFsRef = useRef<any>();
  const [value, setValue] = useState('期末');
  const Divstyle: React.CSSProperties = {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    marginRight: '15px',
  };

  useImperativeHandle(ref, () => ({
    show: (params: any) => {
      debugger;
      diaParams.current = params;
      if (params.width) {
        props = { ...props, width: params.width, height: params.height };
      }

      setVisible(true);
      setIsFormulaModalOpen(false);
      setTimeout(() => {
        setRealCPASTableRef('资产表', '期末');
      }, 200);
      setCreateTabla('资产表');
      setCalculationFormulaSystem(
        params.rowCalculationFormulaSystem ? params.rowCalculationFormulaSystem : '',
      );
      CalculationFormula.current = params.CalculationFormulaSystem
        ? params.CalculationFormulaSystem
        : '';
    },
    closeDia: () => {
      setVisible(false);
    },
    getInstance: () => {
      return popupRef.current.instance();
    },
    getCalculationFormulaSystem: () => {
      return CalculationFormulaSystem;
    },
    getCalculationFormula: () => {
      return CalculationFormula.current;
    },

    clearCon: () => {
      debugger;
      return popupRef.current.instance().dispose();
    },
  }));

  const onOk = () => {
    if (diaParams.current?.okCallback) {
      diaParams.current?.okCallback(CalculationFormulaSystem);
    }
    setVisible(false);
  };

  const onCancel = () => {
    if (diaParams.current?.cancelCallback) {
      diaParams.current?.cancelCallback();
    }
    setVisible(false);
  };

  const onClose = () => {
    if (diaParams.current?.onClose) {
      diaParams.current?.onClose();
    }
    setVisible(false);
  };
  const getRealCPASTableRef = () => {
    if (cpasTableFsRef.current) {
      const realHandSonGridRef = cpasTableFsRef.current.handsonTableFs.current;
      return realHandSonGridRef;
    }
    return null;
  };
  const handleChange = (e: any) => {
    // setValue(e.value);
    setCalculationFormulaSystem(e.value);
    // CalculationFormula.current = e.value; // 此思路不行，还是在一个公式出入框里做最后的提取
  };
  const onSelectionData = ({ selectedItem }: any) => {
    // debugger
    let vValue = '';
    if (['现金流量表', '利润表'].includes(selectedItem.displayName)) {
      vValue = '本期';
    } else {
      vValue = '期末';
    }
    setValue(vValue);
    setCreateTabla(selectedItem.displayName);
    setRealCPASTableRef(selectedItem.displayName, vValue);
  };
  const setRealCPASTableRef = async (tableName: string, dateTime: string) => {
    const realrealHandSonGridRefRef = getRealCPASTableRef();
    debugger;
    const serverData = await realrealHandSonGridRefRef?.loadTableByServer(
      `${sjnd}_试算平衡-${tableName}_${dateTime}`,
    );
    if (realrealHandSonGridRefRef) {
      let cmap = '',
        cmap2 = '本期审定期初数';
      if (diaParams.current?.isAudit === '审定') {
        if (dateTime !== '期初') {
          cmap = `${dateTime}审定数`;
        }
      } else {
        if (dateTime === '上期' || dateTime === '期初') {
          cmap = `${dateTime}审定数`;
        } else {
          cmap = `${dateTime}未审数`;
        }
      }
      serverData.header.forEach((a: any, index: number) => {
        if (index > 1) {
          if (![cmap, '借方', 'rowConfig', cmap2].includes(a.label.trim())) {
            a.config.hidden = true;
            a?.children?.forEach((b: any) => {
              b.config.hidden = true;
            });
          }
        }
      });
      realrealHandSonGridRefRef.reloadTable(serverData, 'fs', null, true);
    }
  };

  const onRadioChange = (e: any) => {
    setValue(e);
    debugger;
    setRealCPASTableRef(createTabla, e);
  };

  // 优化 dbCellClick 函数
  const dbCellClick = useCallback(
    (arg: any, coords: any, TD: any, maps: any, tabName: any) => {
      if (maps.rowMap?.split('-')?.length === 2) {
        maps.rowMap = maps.rowMap.split('-')[1]; // 此提取为展示公式，系统公式还是不变，新的版本的模版不存在
        notify('提示： 此模版是老版本，请切换新的版本的模版', 'error', 2000);
        // return;
      }
      if (maps.columnMap?.includes('ItemName')) {
        notify('不能选择项目列', 'error', 1000);
      } else {
        // 更新公式处理，确保 tabName 有值
        const formula = `CP_CELL("{sjnd}_试算平衡-${createTabla}${
          isFormulaModalOpen ? `_${tabName}` : ''
        }","${isFormulaModalOpen ? `${tabName}_` : ''}${maps.rowMap}","${maps.columnMap}")`;
        if (!CalculationFormulaSystem) {
          setCalculationFormulaSystem(formula);
        } else {
          setCalculationFormulaSystem((prev) => `${prev} + ${formula}`);
        }
      }
    },
    [createTabla, isFormulaModalOpen, CalculationFormulaSystem],
  );

  /**
   *
   * @param nameKey 切换Tabs 的名字。
   * @returns
   */
  const changeTemplete = (nameKey: string = 'qmqc') => {
    if (isFormulaModalOpen) {
      if (!['现金流量表', '利润表'].includes(createTabla)) {
        return (
          <Radio.Group
            onChange={(e) => {
              onRadioChange(e.target.value);
            }}
            value={value}
          >
            <Radio value={'期末'}>期末</Radio>
            <Radio value={'期初'}>期初</Radio>
          </Radio.Group>
        );
      } else {
        return (
          <Radio.Group
            onChange={(e) => {
              onRadioChange(e.target.value);
            }}
            value={value}
          >
            <Radio value={'本期'}>本期</Radio>
            <Radio value={'上期'}>上期</Radio>
          </Radio.Group>
        );
      }
    } else {
      return <></>;
    }
  };
  return (
    <>
      <Popup
        ref={popupRef}
        visible={visible}
        title={diaParams.current?.title}
        width={props?.width ? props?.width : 800}
        height={props?.height ? props?.height : 150}
        // {...props}
        onContentReady={(e: any) => {
          console.log('li,eee', e);
        }}
        // dragOutsideBoundary={true}
        resizeEnabled={true}
        onHiding={() => onClose()} // x的关闭
        toolbarItems={[
          {
            widget: 'dxButton',
            toolbar: 'bottom',
            location: 'after',

            options: {
              type: '',
              text: diaParams.current?.cancelText || intl('pub.cancel', '否'),
              onClick: () => {
                onCancel();
              },
            },
          },
          {
            widget: 'dxButton',
            toolbar: 'bottom',
            location: 'after',
            options: {
              text: diaParams.current?.okText || intl('pub.ok', '是'),
              type: 'default',
              onClick: () => onOk(),
            },
          },
        ]}
        contentRender={() => (
          <>
            <div
              style={{
                display: 'flex',
                alignItems: 'center',
                height: '100px',
              }}
            >
              <TextArea
                value={CalculationFormulaSystem}
                maxLength={5000}
                height={80}
                onValueChanged={handleChange} // 输入框内容变化时触发
                // onFocusIn={onFocusInFormula}
                label={`${diaParams.current?.IndicatorName}-系统取数计算公式`}
              />
              <div
                style={{
                  // height: '70px',
                  display: 'flex',
                  alignItems: 'center',
                  flexDirection: 'column',
                }}
              >
                <Button
                  height={'30'}
                  style={{ marginLeft: '10px', marginBottom: '5px' }}
                  onClick={() => {
                    CalculationFormula.current = '';
                    setCalculationFormulaSystem('');
                  }}
                  text="清空公式"
                />
              </div>
            </div>
            <div className="BalanceLRXJBCRadio">
              <div style={Divstyle}>
                {/* <div>年度：{sjnd} </div> */}
                <div style={{ marginLeft: '0px' }}>表名 ：</div>
                <SelectBox
                  width={150}
                  dataSource={[
                    { displayName: '资产表' },
                    { displayName: '负债表' },
                    { displayName: '利润表' },
                    { displayName: '现金流量表' },
                  ]}
                  displayExpr="displayName"
                  valueExpr="displayName"
                  value={createTabla}
                  onSelectionChanged={onSelectionData}
                  dropDownOptions={{ width: '200px' }}
                />
              </div>
              {changeTemplete()}
              <Button
                height={'30'}
                style={{ marginLeft: '10px' }}
                onClick={() => {
                  setIsFormulaModalOpen(!isFormulaModalOpen);
                }}
                text="跨期间公式"
              />
            </div>
            <div style={{ height: '80%' }} className="tb_capstableContent">
              <CpasTableFs
                // height={'300px'}
                tabGroup="fs-tab"
                tabLevel={2}
                ieType="json,draft"
                numberZeroReplace={cpasTableZeroReplace}
                type={'fs'}
                name={`${value}`}
                ref={cpasTableFsRef}
                dbCellClick={dbCellClick}
              />
            </div>
          </>
        )}
      />
    </>
  );
});

export default PopupDevComponentsFormalu;
